import React, { useEffect, useState } from "react";
import { GroupProps, MeshProps, ThreeEvent, useFrame, useLoader, useThree } from "@react-three/fiber";
import { GLTFLoader } from 'three-stdlib';
import { BufferGeometry, Material, Mesh, Plane, Vector3 } from "three";
import { vec3 } from "@react-three/rapier";


export function DragablePart(props: MeshProps & { geometry: any, material: any, truePosition: Vector3, startPosition: Vector3, true: any, onDragging: ((set: boolean) => void) }) {

    const floorPlane = new Plane(vec3({ x: 0, y: 1, z: 0 }))
    const [pos, setPos] = useState(props.startPosition)
    const [drag, enableDrag] = useState(false)
    const state = useThree()
    let planeIntersectPoint = vec3();

    const onPointerUp = () => {
        props.onDragging(false)
        enableDrag(false)
    }
    useEffect(() => {
        if (props.truePosition == pos) {
            props.true.true = true
        }
        window.addEventListener("pointerup", onPointerUp)
    })

    useFrame(() => {
        if (drag) {
            state.raycaster.ray.intersectPlane(floorPlane, planeIntersectPoint)
            setPos(vec3({ x: planeIntersectPoint.x, y: 0, z: planeIntersectPoint.z }))
            if (pos.x - 1 < props.truePosition.x &&
                pos.y - 1 < props.truePosition.y &&
                pos.z - 1 < props.truePosition.z &&
                pos.x + 1 > props.truePosition.x &&
                pos.y + 1 > props.truePosition.y &&
                pos.z + 1 > props.truePosition.z
            ) {
                setPos(props.truePosition)
            }
        }
    })
    return (
        <>
            <mesh
                onPointerDown={
                    (e) => {
                        if (!props.true.true) {
                            props.onDragging(true)
                            enableDrag(true)
                            e.stopPropagation()
                        }
                    }
                }
                name={props.name}
                position={pos}
                geometry={props.geometry}
                material={props.material}
            />
        </>
    );
}

